package com.jyun;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class GzipResponse extends HttpServletResponseWrapper {
    private HttpServletResponse response;
    private GzipOutputStream gzipOutputStream;
    private PrintWriter writer;
    public GzipResponse(HttpServletResponse response) {
        super(response);
        this.response=response;
    }
    public ServletOutputStream getOutputStream() throws IOException {
        if (gzipOutputStream == null)
            gzipOutputStream = new GzipOutputStream(response);
        return gzipOutputStream;
    }

    public PrintWriter getWriter() throws IOException {
        if (writer == null)
            writer = new PrintWriter(new OutputStreamWriter(
                    new GzipOutputStream(response), "UTF-8"));
        return writer;
    }

    // 压缩后数据长度会发生变化 因此将该方法内容置空
    public void setContentLength(int contentLength) {
    }

    public void flushBuffer() throws IOException {
        gzipOutputStream.flush();
    }

    public void finishResponse() throws IOException {
        if (gzipOutputStream != null)
            gzipOutputStream.close();
        if (writer != null)
            writer.close();
    }
}
